const app = getApp();
const {htmlEncode, checkInputCode} = require('../../utils/util.js')
const api = require("../../utils/apiInstance");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: app.globalData.baseUrl,
        fileUrl: app.globalData.fileUrl,
        tempFilePaths: '',
        deadlineArray: ['立即', '七天', '十五天', '一个月'],
        riskTypeArray: ['人员/外来人员', '设备隐患', '原材料/辅料', '操作方法', '环境', '测量/检测'],
        riskLevelArray: ['一般', '重大'],
        deadlineIndex: null,
        riskTypeIndex: null,
        areaIndex: null,
        areaLevel1Index: null,
        areaLevel2Index: null,
        areaLevel3Index: null,
        areaLevel1: null,
        areaLevel2: null,
        areaLevel3: null,
        imgList: [],
        deptList: [],
        areaList: [],
        areaLevel1List: [],
        areaLeve2List: [],
        areaLeve3List: [],
        location: null,
        content: null,
        suggest: null,
        sapId: null,
        bigSearchShow: false,
        bigSearchType: "",
        saferFlag: false,
        dutyDept: "",
        searchDataList: [],
        imgSuccessLoaded: [],
        proposeDept: "",
        proposeByName: "",
        isMutiSelectShow: false,
        isShowZgQx: false,
        bigSearchShowType: '',
        staffList: [],
        isShengChanBu: false,
        personnelIndex: '',
        selfDept: false,
        personnelList: ['AS PM11', 'AS PM12', 'AS PM13', '复卷机'],
    },
    selfDeptChange(e) {
        this.setData({
            selfDept: e.detail.value
        })
        if (e.detail.value) {
            this.getStaffBySapId();
        }
    },
    getAllDept: function () {
        const that = this;
        wx.request({
            url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
            method: 'GET',
            header: {
                'Content-Type': 'application/json' // 请求头
            },
            success(res) {
                console.log('获取所有部门信息:', res.data);
                const data = res.data;
                that.setData({
                    deptList: data.data
                })
            }
        });
    },
    riskLevelChange: function (e) {
        console.log('隐患分级选择变化，携带值为', e.detail.value)
        this.setData({
            riskLevelIndex: e.detail.value
        })
    },
    initSapId: function () {
        const userInfo = wx.getStorageSync('userinfo');
        this.setData({
            sapId: userInfo.siocSapNo,
            proposeDept: userInfo.siocDepartCode,
            proposeByName: userInfo.siocCnName
        })
    },

    deadlineChange: function (e) {
        this.setData({
            deadlineIndex: e.detail.value
        })
    },
    riskTypeChange: function (e) {
        this.setData({
            riskTypeIndex: e.detail.value
        })
    },
    areaChange: function (e) {
        this.setData({
            areaIndex: e.detail.value
        })
        this.setData({
            'areaLevel1': '',
            'areaLevel2': '',
            'areaLevel3': '',
        })

        const that = this;
        wx.request({
            url: (that.data.baseUrl + '/tissueArea/wx/getLevel1Area?area=' + that.data.areaList[that.data.areaIndex]).replaceAll('#', '%23'),
            method: 'GET',
            header: {
                'Content-Type': 'application/json' // 请求头
            },
            success(res) {
                const data = res.data;
                that.setData({
                    areaLevel1List: [data.data.map(item => {
                        return {name: item}
                    })],
                    areaLevel1Index: null,
                    areaLevel2Index: null,
                    areaLevel3Index: null,
                })
            }
        });
    },
    areaLevel1Change: function (e) {
        this.setData({
            areaLevel1Index: e.detail.value
        })
        const that = this;
        wx.request({
            url: (that.data.baseUrl + '/tissueArea/wx/getLevel2Area?area=' + that.data.areaList[that.data.areaIndex] + '&level1Area=' + that.data.areaLevel1List[that.data.areaLevel1Index].replaceAll('&', '%26')).replaceAll('#', '%23'),
            method: 'GET',
            header: {
                'Content-Type': 'application/json' // 请求头
            },
            success(res) {
                console.log('获取二级区域信息:', res.data);
                const data = res.data;
                that.setData({
                    areaLevel2List: data.data,
                    areaLevel2Index: null,
                    areaLevel3Index: null,
                })
            }
        });
    },
    areaLevel2Change: function (e) {
        console.log('二级区域选择改变，携带值为', e)
        this.setData({
            areaLevel2Index: e.detail.value
        })
        const that = this;
        wx.request({
            url: (that.data.baseUrl + '/tissueArea/wx/getLevel3Area?area=' + that.data.areaList[that.data.areaIndex] + '&level1Area=' + that.data.areaLevel1List[that.data.areaLevel1Index].replaceAll('&', '%26') + '&level2Area=' + that.data.areaLevel2List[that.data.areaLevel2Index]).replaceAll('#', '%23'),
            method: 'GET',
            header: {
                'Content-Type': 'application/json' // 请求头
            },
            success(res) {
                console.log('获取三级区域信息:', res.data);
                const data = res.data;
                that.setData({
                    areaLevel3List: data.data,
                    areaLevel3Index: null,
                })
            }
        });
    },
    areaLevel3Change: function (e) {
        console.log('三级区域选择改变，携带值为', e)
        this.setData({
            areaLevel3Index: e.detail.value
        })
    },

    async getAllArea () {
        const result = await api.get("/tissueArea/wx/getAllArea");
        this.setData({
            areaList: result.data
        })
    },

    mutiSelect(e) {
        console.log('mutiSelecte', e);
        this.setData({
            'areaLevel1': e.detail[0]?.name || '',
            'areaLevel2': e.detail[1]?.name || '',
            'areaLevel3': e.detail[2]?.name || '',
        })
    },

    showMutiSelect() {
        if (this.data.areaLevel1List.length == 0) {
            wx.showModal({
                title: '提示',
                content: '请先选择隐患区域',
                showCancel: false
            })
            return;
        }
        this.setData({
            isMutiSelectShow: true
        })
    },

    submitForm(e) {
        wx.showLoading({
            title: '提交中',
            mask: true
        })
        const that = this;
        const formData = e.detail.value;
        console.log('form发生了submit事件，携带数据为：', formData);
        formData.imgList = that.data.imgList;
        formData.dutyDept = that.data.dutyDept;
        formData.areaLevel1 = that.data.areaLevel1
        formData.areaLevel2 = that.data.areaLevel2
        formData.areaLevel3 = that.data.areaLevel3
        formData.selfDept = that.data.selfDept
        let errMsg = "";
        if (!formData.area) {
            errMsg = errMsg + "隐患区域不能为空;";
        }
        if (!formData.areaLevel1) {
            errMsg = errMsg + "一级区域不能为空;";
        }
        if (!formData.location) {
            errMsg = errMsg + "具体位置不能为空;";
        }
        if (formData.imgList.length < 1) {
            errMsg = errMsg + "隐患图片不能为空;";
        }
        if (!formData.content) {
            errMsg = errMsg + "隐患内容不能为空;";
        }
        if (that.data.saferFlag) {
            if (!formData.deadline && that.data.selfDept) {
                errMsg = errMsg + "整改期限不能为空;";
            }
            if (!formData.corrector && that.data.selfDept) {
                errMsg = errMsg + "整改人不能为空;";
            }
            if (!formData.dutyDept && !that.data.selfDept) {
                errMsg = errMsg + "责任部门不能为空;";
            }
            if (!formData.dutyDeptPa && that.data.isShengChanBu) {
                errMsg = errMsg + "Personnel Area不能为空;";
            }
        }

        if (!formData.riskType) {
            errMsg = errMsg + "隐患类型不能为空;";
        }
        if (!formData.suggest) {
            errMsg = errMsg + "整改建议不能为空;";
        }

        if (checkInputCode(formData.location)) {
            errMsg = errMsg + "位置不允许输入特殊字符;";
        }

        if (checkInputCode(formData.content)) {
            errMsg = errMsg + "问题情况不允许输入特殊字符;";
        }

        if (checkInputCode(formData.suggest)) {
            errMsg = errMsg + "排查措施不允许输入特殊字符;";
        }

        if (that.data.imgSuccessLoaded.length > 0 && that.data.imgSuccessLoaded.filter(item => item == 0).length > 0) {
            errMsg = errMsg + "请检查是否上传正确的图片;";
        }
        console.log('form发生了submit事件，携带数据为：', formData);
        if (errMsg.length > 0) {
            wx.hideLoading()
            wx.showModal({
                title: '提示',
                content: errMsg,
                showCancel: false
            })
            return;
        }

        // 向服务器提交表单数据
        wx.request({
            url: that.data.baseUrl + '/tissueRisk/wx/addRmStaff',
            method: 'POST',
            header: {
                'userNo': wx.getStorageSync('userinfo').siocSapNo // 请求头
            },
            data: formData,
            success: function (res) {
                wx.hideLoading()
                console.log('表单提交成功', res);
                if (200 == res.data.code) {
                    that.setData({
                        tempFilePaths: '',
                        location: null,
                        content: null,
                        suggest: null,
                        deadlineIndex: null,
                        riskTypeIndex: null,
                        areaIndex: null,
                        areaLevel1Index: null,
                        areaLevel2Index: null,
                        areaLevel3Index: null
                    });
                    wx.showModal({
                        title: '提示',
                        content: res.data.msg,
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/pages/tissueRisk-list/tissueRisk-list'
                                })
                            }
                        }
                    })
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    });
                }
            },
            fail: function (err) {
                wx.hideLoading()
                console.error('表单提交失败', err);
                wx.showToast({
                    title: '表单提交失败',
                    icon: 'none'
                });
            }
        });
    },

    ViewImage(e) {
        let urls = [];
        let current = this.data.fileUrl + e.currentTarget.dataset.url;
        for (let key in this.data.imgList) {
            urls.push(this.data.fileUrl + this.data.imgList[key]);
        }
        ;
        wx.previewImage({
            urls: urls,
            current: current
        });
    },

    DelImg(e) {
        wx.showModal({
            title: '删除图片',
            content: '确定要删除这张图片',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
                    this.data.imgSuccessLoaded.splice(e.currentTarget.dataset.index, 1);
                    this.setData({
                        imgList: this.data.imgList,
                        imgSuccessLoaded: this.data.imgSuccessLoaded
                    })
                }
            }
        })
    },

    ChooseImage: function () {
        const that = this;
        wx.chooseMedia({
            count: 1, // 一次只能选择一张图片
            sizeType: ['original', 'compressed'], // 压缩图片
            sourceType: ['album', 'camera'], // 从相册选择
            async success(res) { // 将图片上传到服务器

                wx.uploadFile({
                    url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
                    filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
                    name: 'file', // 服务端用于接收文件的参数名
                    success(res) {
                        let json = JSON.parse(res.data);
                        let tempArray = [];
                        tempArray.push(json.fileName);
                        // 上传成功，做一些处理
                        if (that.data.imgList.length != 0) {
                            that.setData({
                                imgList: that.data.imgList.concat(tempArray)
                            })
                        } else {
                            that.setData({
                                imgList: tempArray
                            })
                        }
                    }
                })
            }
        })
    },

    imageLoad(e) {
        this.data.imgSuccessLoaded.push(1)
        this.setData({
            imgSuccessLoaded: this.data.imgSuccessLoaded
        })
    },

    imageError(e) {
        this.data.imgSuccessLoaded.push(0)
        this.setData({
            imgSuccessLoaded: this.data.imgSuccessLoaded
        })
    },

    getStaffByDept: function (dutyDept) {
        return new Promise((reslove, reject) => {
            const that = this;
            wx.request({
                url: that.data.baseUrl + '/staffInfo/wx/getStaffByDept?dept=' + dutyDept,
                method: 'GET',
                header: {
                    'Content-Type': 'application/json' // 请求头
                },
                success(res) {
                    console.log('获取部门员工信息:', res.data);
                    const data = res.data;


                    that.setData({
                        staffList: data.data,
                    })

                    return reslove(data.data)

                }
            });
        })

    },

    getStaffBySapId: function () {
        const that = this;
        wx.request({
            url: that.data.baseUrl + '/staffInfo/wx/getStaffBySapId?sapId=' + wx.getStorageSync('userinfo').siocSapNo,
            method: 'GET',
            header: {
                'Content-Type': 'application/json' // 请求头
            },
            success(res) {
                console.log('获取部门员工信息:', res.data);
                const data = res.data;
                that.setData({
                    staffList: data.data,
                })
            }
        });
    },

    async doBigSearchShow(e) {
        const that = this
        const tempArray = [];
        const typeMethods = {
            staff: async () => {
                let staffList = [];
                if (this.data.staffList == 0) {
                    staffList = await this.getStaffByDept(this.data.dutyDept)
                } else {
                    staffList = this.data.staffList
                }
                if (staffList.length == 0) {
                    wx.showToast({
                        title: '暂无整改人指派',
                        icon: 'none'
                    });
                    return;
                } else {
                    staffList.forEach(item => {
                        tempArray.push({
                            name: item
                        });
                    });

                }
            },
            dept: () => {
                if (that.data.deptList.length == 0) {
                    wx.showToast({
                        title: '暂无部门指派',
                        icon: 'none'
                    });
                    return;
                } else {
                    that.data.deptList.forEach(item => {
                        tempArray.push({
                            name: item
                        });
                    });

                }
            }
        }
        await typeMethods[e.currentTarget.dataset.type]();

        this.setData({
            bigSearchType: e.currentTarget.dataset.type,
            bigSearchShow: true,
            bigSearchShowType: e.currentTarget.dataset.type,
            searchDataList: tempArray
        })

    },

    personnelChange(e) {
        this.setData({
            personnelIndex: e.detail.value
        })
    },
    searchSelect(e) {
        console.log('e', e);
        const params = {}
        params[this.data.bigSearchType == 'staff' ? 'corrector' : 'dutyDept'] = e.detail.name || ""
        if (this.data.bigSearchShowType == 'dept') {
            Object.assign(params, {
                isShengChanBu: e.detail.name == '生产部'
            })
        }
        this.setData({
            ...params
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.getAllArea();
        this.initSapId();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})